package com.zx.idc.backend.gui.api.ws.services.axis2;

import com.zx.idc.common.constants.CommonConstant;
import com.zx.idc.common.util.FileCopyUtils;
import org.apache.axis2.transport.http.AxisServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@Configuration
public class AxisConfig {

    private static final Logger LOG = LoggerFactory.getLogger(AxisConfig.class);

    @Bean
    public ServletRegistrationBean axisServlet() throws UnsupportedEncodingException {
        ServletRegistrationBean axisServlet = new ServletRegistrationBean();
        axisServlet.setServlet(new AxisServlet());
        axisServlet.addUrlMappings("/services/*");
        String path = this.getClass().getResource("/servicesPath").getPath();
        if (path.toLowerCase().startsWith("file:")) {
            path = path.substring(5);
        }
        if (path.indexOf("!") != -1) {
            try {
                FileCopyUtils.copy("servicesPath/services/conf/META-INF/services.xml");
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
            path = path.substring(0, path.lastIndexOf("/", path.indexOf("!"))) + "/servicesPath";
        }
        path = URLDecoder.decode(path, CommonConstant.DEFAULT_ENCODE);
        axisServlet.addInitParameter("axis2.repository.path", path);
        axisServlet.setLoadOnStartup(1);
        return axisServlet;
    }
}
